"""
Case Type   : 发布订阅
Case Name   : 一个发布对应不同传输方式订阅，且订阅在不同数据库
Create At   : 2022/11/08
Owner       : opentestcase026
Description :
    1.订阅端创建两个数据库
    2.两个集群创建表
    3.创建发布
    4.分别在两个数据库中创建二进制和非二进制传输方式的订阅
    5.发布端表中插入数据
    6.查询订阅端数据是否同步
    7.发布端删除数据
    8.查询订阅端数据是否同步
    9.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.成功
    6.订阅端同步数据
    7.成功
    8.数据同步
    9.成功
History     :
"""

import os
import time
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.com_pub = Common()
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.db_name = ['db_pubsub_0202_1', 'db_pubsub_0202_2']
        self.tb_name = 't_pubsub_0202'
        self.subname = ['sub_pubsub_0202_1', 'sub_pubsub_0202_2']
        self.pubname = 'pub_pubsub_0202'
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        self.wal_level = self.com_pub.show_param("wal_level")
        text = '-----查询集群状态，配置白名单，发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host replication {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32  sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host replication {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32 sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'订阅端配置白名单失败:{text}')

    def test_pub_sub(self):
        text1 = '-----step1:订阅端创建两个数据库;expect:创建成功-----'
        self.log.info(text1)
        create_db = f"create database {self.db_name[0]};" \
                    f"create database {self.db_name[1]};"
        create_res = self.commsh_sub.execut_db_sql(create_db,
                                            env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(create_res)
        self.assertEqual(
            create_res.count(self.constant.CREATE_DATABASE_SUCCESS),
            2, f'执行失败:{text1}')

        text = "-----step2:两个集群创建表;expect:成功-----"
        self.log.info(text)
        create_tb = f"drop table if exists {self.tb_name} cascade;" \
                    f"create table {self.tb_name}(" \
                    f"c_int int primary key, c_text text);"
        pub_res = self.commsh_pub.execut_db_sql(create_tb,
                                                sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, pub_res,
                      f'执行失败:{text}')
        self.assertEqual(pub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                         2, f'执行失败:{text}')
        for name in self.db_name:
            sub_res = self.commsh_sub.execut_db_sql(
                create_tb, self.user_param_sub,
                name, macro.DB_ENV_PATH_REMOTE1)
            self.log.info(sub_res)
            self.assertIn(self.constant.DROP_TABLE_SUCCESS, sub_res,
                          f'执行失败:{text}')
            self.assertEqual(sub_res.count(self.constant.TABLE_CREATE_SUCCESS),
                             2, f'执行失败:{text}')

        text = "-----step3:创建发布;expect:成功-----"
        self.log.info(text)
        create_pub = f"drop publication if exists {self.pubname};" \
                     f"create publication {self.pubname} for all tables;"
        pub_res = self.commsh_pub.execut_db_sql(create_pub,
                                                sql_type=self.user_param_pub)
        self.log.info(pub_res)
        self.assertIn(self.constant.drop_pub_succ_msg, pub_res,
                      f'执行失败:{text}')
        self.assertIn(self.constant.create_pub_succ_msg, pub_res,
                      f'执行失败:{text}')

        text = "-----step4:分别在两个数据库中创建二进制和非二进制传输方式的订阅;expect:成功-----"
        self.log.info(text)
        guc_res = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, guc_res,
                      f'执行失败:{text}')
        for i in range(2):
            create_sub = \
                f"drop subscription if exists {self.subname[i]};" \
                f"create subscription {self.subname[i]} connection " \
                f"'host={self.pri_userdb_pub.db_host} " \
                f"port={self.port} user={self.pri_userdb_pub.db_user} " \
                f"dbname={self.pri_userdb_pub.db_name} " \
                f"password={self.pri_userdb_pub.ssh_password}' " \
                f"publication {self.pubname} with (binary={i});"
            sub_res = self.commsh_sub.execut_db_sql(
                create_sub, self.user_param_sub,
                self.db_name[i], macro.DB_ENV_PATH_REMOTE1)
            self.log.info(sub_res)
            self.assertIn(self.constant.drop_sub_succ_msg, sub_res,
                          f'执行失败:{text}')
            self.assertIn(self.constant.create_sub_succ_msg, sub_res,
                          f'执行失败:{text}')

        text = "-----step5:发布端表中插入数据;expect:成功-----"
        self.log.info(text)
        sql_cmd = f"insert into {self.tb_name} values(1, 'first%');"
        pub_result = self.commsh_pub.execut_db_sql(sql_cmd,
                                                   sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, pub_result,
                      f'执行失败:{text}')

        text = "-----step6:查询订阅端数据是否同步;expect:数据同步-----"
        self.log.info(text)
        time.sleep(6)
        sql_select = f"select * from {self.tb_name};"
        for dbname in self.db_name:
            select_res = self.commsh_sub.execut_db_sql(
                sql_select, self.user_param_sub,
                dbname, macro.DB_ENV_PATH_REMOTE1)
            self.log.info(select_res)
            self.assertIn('1 | first%', select_res, f'执行失败:{text}')

        text = "-----step7:发布端删除数据;expect:成功-----"
        self.log.info(text)
        sql_cmd = f"delete from {self.tb_name};"
        pub_result = self.commsh_pub.execut_db_sql(sql_cmd,
                                                   sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertIn(self.constant.DELETE_SUCCESS_MSG, pub_result,
                      f'执行失败:{text}')

        time.sleep(6)
        text = "-----step8:查询订阅端数据是否同步;expect:数据同步-----"
        self.log.info(text)
        for dbname in self.db_name:
            select_res = self.commsh_sub.execut_db_sql(
                sql_select, self.user_param_sub,
                dbname, macro.DB_ENV_PATH_REMOTE1)
            self.log.info(select_res)
            self.assertIn('0 rows', select_res, f'执行失败:{text}')

    def tearDown(self):
        text = "-----step9:清理环境;expect:成功-----"
        self.log.info(text)
        drop_sub_res = list()
        for i in range(2):
            sql_cmd = f"drop subscription if exists {self.subname[i]};"
            drop_sub = self.commsh_sub.execut_db_sql(
                sql_cmd, self.user_param_sub,
                self.db_name[i], macro.DB_ENV_PATH_REMOTE1)
            self.log.info(drop_sub)
            drop_sub_res.append(drop_sub)
        sql_cmd = f"drop publication if exists {self.pubname};"
        drop_pub_res = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(drop_pub_res)
        sql_cmd = f"drop table if exists {self.tb_name};"
        pub_droptb = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(pub_droptb)
        drop_db = f"drop database {self.db_name[0]};" \
                  f"drop database {self.db_name[1]};"
        sub_dropdb = self.commsh_sub.execut_db_sql(
            drop_db, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_dropdb)
        guc_res1 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host    replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(guc_res1)
        guc_res2 = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host    replication  {self.pri_userdb_pub.db_user} '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res2)
        res_wal = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(res_wal)
        pub_restartdb = self.commsh_pub.restart_db_cluster()
        self.assertTrue(pub_restartdb, f'订阅端重启数据库失败:{text}')
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_res[0],
                      f'删除订阅1失败:{text}')
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_res[1],
                      f'删除订阅2失败:{text}')
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_res,
                      f'删除发布失败:{text}')
        self.assertEqual(sub_dropdb.count(self.constant.DROP_DATABASE_SUCCESS),
                         2, f'订阅端删除数据库失败:{text}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, pub_droptb,
                      f'发布端删除表失败:{text}')
        self.assertTrue(guc_res1, f'发布端删除白名单失败:{text}')
        self.assertTrue(guc_res2, f'订阅端删除白名单失败:{text}')
        self.assertTrue(res_wal, f'发布端恢复wal_level参数失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
